//
//  StringCommonfactor.swift
//  AlgorithmOne
//
//  Created by 刘彬彬 on 2020/3/12.
//  Copyright © 2020 LBB. All rights reserved.
//

import Foundation

class CommonFactor {
    func solution(_ string1:String,_ string2:String) -> String {
//        if !ziMu(string1) || !ziMu(string2) {return ""}
        var temp = ""
        var target1 = string1
        var target2 = string2
        if string1.count < string2.count {
            temp = target1;
            target1 = target2;
            target2 = temp;
        }
        if target1.range(of: target2) == nil {return "null"}
//        else {
//            //特殊情况，字符串全是一个字母,并且target2本身就是最大公因数
//            if commonString(target2) {
//                if target1.count % target2.count == 0 {
//                    return target2
//                }
//            }
//        }
        
        var targetString = ""
        var returnString = ""
        
        for s in target1 {
            if target2.range(of: String(s)) == nil {return "null"}
        }
        for s in target2 {
            targetString = targetString.appending(String(s))
            if target1.count % String(targetString).count != 0 {continue}
            else {
                var segmentation = ""
                for j in target1 {
                    segmentation = segmentation.appending(String(j))
                    if segmentation.count == targetString.count {
                        //如果长度相同
                        if segmentation == targetString {
                            //并且字符串相同，分割的segmentation清空，重新循环，知道循环结束
                            segmentation = ""
                        } else {
                            break
                        }
                    }
                }
                if targetString.count > returnString.count && target1.count%targetString.count == 0 && target2.count%targetString.count == 0 {returnString = targetString;}
            }
        }
        return returnString
    }
    
    //判断string的所有字符时候为同一个字符
    func commonString(_ string:String) -> Bool {
        var i = 0
        var tempString = ""
        for s in string {
            if i == 0 {
                tempString = String(s)
            }
            if tempString != String(s) {
                return false
            }
            i += 1
        }
        return true
    }
    
    func ziMu(_ string:String) -> Bool {
        let reg = "^[a-zA-Z]+$"
        let pre = NSPredicate(format: "SELF MATCHES %@", reg)
        for i in string {
            if !pre.evaluate(with: i) {return false}
        }
        return true
    }
}
